package com.mrzhou.auth.support;

import com.mrzhou.auth.service.CloudUserDetails;
import com.mrzhou.auth.utils.TokenUtil;
import com.mrzhou.core.tool.utils.Func;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * 用以扩展jwt的携带的参数
 */
public class CloudJwtTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        CloudUserDetails userDetail = (CloudUserDetails) oAuth2Authentication.getUserAuthentication().getPrincipal();
        Map<String, Object> info = new HashMap<>();
        info.put(TokenUtil.CLIENT_ID, TokenUtil.getClientIdFromHeader());
        info.put(TokenUtil.USER_ID, Func.toStr(userDetail.getUserId()));
        info.put(TokenUtil.AVATAR, userDetail.getAvatar());
        info.put(TokenUtil.ACCOUNT, userDetail.getAccount());
        info.put(TokenUtil.ROLE_NAME, userDetail.getRoleName()); // 权限名称, 接口鉴权比较此参数
        info.put(TokenUtil.NAME, userDetail.getName());
        info.put(TokenUtil.REAL_NAME, userDetail.getRealName());
        info.put(TokenUtil.PHONE, userDetail.getPhone());
        info.put(TokenUtil.EMAIL, userDetail.getEmail());
        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);
        return oAuth2AccessToken;
    }
}
